package interview;

import java.util.Stack;

class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

class No1 {

    public static void main(String[] args) {
        No1 main = new No1();
        System.out.println(main.reverseWords("the sky is blue"));
    }

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    public int numIslands(char[][] grid) {
        int count = 0;
        int hight = grid.length;

        return count;
    }

    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        Stack<StringBuffer> stack = new Stack<>();
        StringBuffer buffer = new StringBuffer();
        for (char aChar : chars) {
            if (aChar == ' ' && buffer.length() != 0) {
                stack.push(buffer);
                buffer = new StringBuffer();
                continue;
            }

            if (aChar != ' '){
                buffer.append(aChar);
            }
            //System.out.println(buffer);
        }

        if (buffer.length() != 0){
            stack.push(buffer);
        }

        StringBuilder ret = new StringBuilder();
        while (!stack.isEmpty()) {
            ret.append(stack.pop()+" ");
        }

        return ret.substring(0,ret.length()-1);
    }
}
